package com.yjt.termworks;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.yjt.termworks.fragment.HomeFragment;
import com.yjt.termworks.sql.LoginHelper;
import com.yjt.termworks.sql.MyHelper;
import com.yjt.termworks.utils.SharePreferenceData;

import java.util.Map;

public class LoginActivity extends AppCompatActivity {
    private  EditText userPhone,pwd;
    private CheckBox checkBox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        TextView btn_login = findViewById(R.id.btn_login);
        userPhone= findViewById(R.id.login_phone);
        pwd = findViewById(R.id.login_password);
        checkBox = findViewById(R.id.checkbox);

        getUserData();   // 获取账号密码
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login(view);

            }
        });
    }

    public void getUserData(){
        try {
            Map<String, String> userInfo = SharePreferenceData.getUserData(this);
            String userName = userInfo.get("userName");
            String userPwd = userInfo.get("userPwd");
            userPhone.setText(userName);
            pwd.setText(userPwd);
            checkBox.setChecked(true);
        }catch (Exception e){
            checkBox.setChecked(false);
        }


    }

    private  void login(View view){
        MyHelper myHelper = new MyHelper(view.getContext());
        SQLiteDatabase db = myHelper.getWritableDatabase();


        Cursor cursor = db.rawQuery("select * from USER where phone = ?", new String[]{userPhone.getText().toString()});
        try {
            cursor.moveToNext();
            boolean b = pwd.getText().toString().equals(cursor.getString(3));
            if(b){
                SharePreferenceData.saveUserData(view.getContext(),userPhone.getText().toString(), pwd.getText().toString());
                 SharePreferenceData.saveUserData2(view.getContext(),userPhone.getText().toString());
                Toast.makeText(view.getContext(),"登录成功",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            }else{
                Toast.makeText(view.getContext(),"密码错误",Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){
            Toast.makeText(view.getContext(),"手机号输入错误",Toast.LENGTH_SHORT).show();
        }
        cursor.close();
        db.close();
    }

}